﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using Website.Logger;
using System.Drawing;
using DAL;
using BOL;
using WebLib;
using System.Web.Script.Services;
using System.Web.Services;
using UtilityExtensions;
namespace UILGestion.Control
{
    public partial class ComparativoItemFinSeleccionPanel : System.Web.UI.UserControl
    {

        public List<int> ItemLista
        {
            get
            {
                List<int> ItemLista = new List<int>();

                var lista = (List<ComparativoDevItemInfo>)Session[idRecursoPartirList.Value.ToString()];

                foreach (GridViewRow row in itemGridView.Rows)
                {
                    CheckBox cb = (CheckBox)(row.FindControl("chkEmployeeSelector"));
                    if (cb != null && cb.Checked)
                    {
                        Int32 id = (Int32)itemGridView.DataKeys[row.RowIndex].Value;

                        ItemLista.Add(id);
                    }
                }

                return ItemLista;
            }
        }

        public List<ComparativoDevItemInfo> ItemListaSelec
        {
            get
            {
                List<ComparativoDevItemInfo> ItemLista = new List<ComparativoDevItemInfo>();

                var lista = (List<ComparativoDevItemInfo>)Session[idRecursoPartirList.Value.ToString()];

                foreach (GridViewRow row in itemGridView.Rows)
                {
                    CheckBox cb = (CheckBox)(row.FindControl("chkEmployeeSelector"));
                    if (cb != null && cb.Checked)
                    {
                        int id = (Int32)itemGridView.DataKeys[row.RowIndex].Value;
                        ComparativoDevItemInfo idcofin = lista.Single(p => p.idInternal == id);
                        ItemLista.Add(idcofin);
                    }
                }

                return ItemLista;
            }
        }

        public int idMotivo
        {
            get
            {
                return int.Parse(MotivoDDL.SelectedValue);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                
                if (!this.IsPostBack)
                {
                    idObra.Value = (string)Request.QueryString["idObra"];
                    idComparativo.Value = (string)Request.QueryString["id"];
                    FormatForm();

                }
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

            //FormatForm();

        }
      
        public void LoadRecurso(string orden=default(string))
        {
            try
            {
                
                List<ComparativoDevItemInfo> compitemList =
                    new ComparativoBL().GetComparativoDevItemFromComparativo(int.Parse(idComparativo.Value), orden);

                simbolMoneda.Value = DbUtil.Db.Comparativos.Single(p => p.idInternal == idComparativo.Value.ToInt()).Moneda.simbol;
                Session[idRecursoPartirList.Value.ToString()] = compitemList;

                

                BindDataItem();
                setEstadistica();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        private void FormatForm()
        {


            idRecursoPartirList.Value = Parametros.GenerarID().ToString();
            fechaLabel.Text = DateTime.Now.ToShortDateString();
            
            
            MotivoDDL.DataValueField="idinternal";
            MotivoDDL.DataTextField="descripcion";

            MotivoDDL.DataSource = DbUtil.Db.MotivoItems.Where(P => P.idMotivo == 3).ToList();
            MotivoDDL.DataBind();

            List<ComparativoDevItemInfo> itemList2 = new List<ComparativoDevItemInfo>();
          Session[idRecursoPartirList.Value.ToString()] = itemList2;

        }
        private void resetEmpty()
        {
            if (itemGridView.Rows.Count == 0)
            {
                List<ComparativoDevItemInfo> itemList0 = new List<ComparativoDevItemInfo>();
                ComparativoDevItemInfo itemcero = new ComparativoDevItemInfo();
                itemcero.idInternal = 0;
                itemList0.Add(itemcero);
                itemGridView.DataSource = itemList0;
                itemGridView.DataBind();
                itemGridView.Rows[0].Visible = false;
            }

        }
        private void setEstadistica()
        {
            List<ComparativoDevItemInfo> itema = this.ItemListaSelec;

            
            TotalLabel.Text = String.Format("{0} {1:N}", simbolMoneda.Value, itema.Sum(p => p.totalBase));
            totalDevolucionLabel.Text = String.Format("{0} {1:N}", simbolMoneda.Value, itema.Sum(p => p.disponible));
            totalUpdatePanel.Update();

        }
        private void BindDataItem()
        {

            List<ComparativoDevItemInfo> item =
                (List<ComparativoDevItemInfo>)Session[idRecursoPartirList.Value.ToString()];


            itemGridView.DataSource = item;
            itemGridView.DataBind();
            resetEmpty(); //necesario para add

            seleccionUpdatePanel.Update();
            //partirUpdatePanel.Update();



           



        }
        

        protected void ItemAllSelectChange(object sender, EventArgs e)
        {
            //solo los seleccionados
            //seleccionamos todos los  item
            foreach (GridViewRow row in itemGridView.Rows)
            {
                CheckBox cb = (CheckBox)(row.FindControl("chkEmployeeSelector"));
                cb.Checked = ((CheckBox)sender).Checked;
            }
            UpdatePanelGrilla.Update();
            setEstadistica();

        }
        protected void ItemSelectChange(object sender, EventArgs e)
        {
            //solo los seleccionados
            //seleccionamos todos los  item
                       
            setEstadistica();

        }
        protected string GetSortDirection(string column)
        {

            // By default, set the sort direction to ascending.
            string sortDirection = "ASC";

            // Retrieve the last column that was sorted.

            string sortExpression = ViewState["SortExpression"] as string;

            if (sortExpression != null)
            {
                // Check if the same column is being sorted.
                // Otherwise, the default value can be returned.
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }

            // Save new values in ViewState.
            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }

        protected void gridview_sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {

                string orden = e.SortExpression + " " + GetSortDirection(e.SortExpression);
                
                LoadRecurso(orden);

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }







        }

        
            
    }
}